// noinspection JSAnnotator
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Flex,Button,Row,Col,Form,Input,Checkbox,Space,message } from "antd";
import {createBrowserRouter, useNavigate} from "react-router-dom";//v6
import './login.scss'; 
import {login} from '../../api/account' //与账号相关的 请求方法

import {getUserRoute,dynamic_routes} from '../../router/index'

import {updateRoute} from '../../store/accountSlice'; //获取action 生成器
import {editLoginStatus,changMenu,saveUserInfo} from '../../store/userSlice' //获取action 生成器

import menu_arr,{ getUserMenu } from '../../router/menu' //获取菜单数组

import {useDispatch} from "react-redux";

function Login(props){
    const [messageApi, contextHolder] = message.useMessage();
    const navigate = useNavigate(); //v6 导航hooks
    const dispatch = useDispatch(); //获取 dispatch对象

    // 提交表单
    const onFinish = async (values) => {
        // 当我们提交表单、验证通过后 执行
        console.log('Received values of form: ', values);
        // 1.取表单数据 
        let {username,password} = values;

        // 2.发请求
        try {
            // 用 async + await 获取异步任务的结果
            // await 等待的是then的结果（异步任务成功时的结果）
            let res = await login({account:username,password}); 
          
            // 消息提示
            if(res.code == 0){
                //登录成功
                messageApi.open({
                    type: 'success',
                    content: res.msg,
                });
                // 保存登录凭证：token
                localStorage.setItem("t_k",res.token)
                // 保存用户角色
                localStorage.setItem("user_role",res.role)

                //登录成功，获取角色对就的路由，放到store中，用于：渲染路由、生成菜单、生成面包屑
                //
                console.log("当前角色："+res.role+"\n处理前：",dynamic_routes)
                let router_arr = getUserRoute(res.role,dynamic_routes)
                console.log("处理后：",router_arr)

                // start
                let routeConfig = router_arr;

                // 定义 RouteElement 组件
                const RouteElement = ({ element: Element }) => {
                    const elementInstance = Element();
                    return <Element {...elementInstance.props} />;
                };

                // 创建路由器
                const routes = createBrowserRouter(routeConfig.map(({ path, element }) => ({
                    path,
                    element: <RouteElement element={element} />,
                })));

                // end
                dispatch(updateRoute( [routeConfig[0]] ))

                // 更新一下登录的状态
                dispatch(editLoginStatus(true))

                // 计算出当前角色的菜单、保存
                let menu = getUserMenu(res.role,menu_arr);
                console.log(menu)
                dispatch(changMenu(menu)) //保存菜单到redux中，并持久化了

                // 保存用户的信息到redux
                let userInfo = {
                    uname:username, //来自表单
                    avatar:"https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png"
                }
                dispatch(saveUserInfo(userInfo))

                //跳转页面
                navigate("/admin/index")
            }else{
                messageApi.open({
                    type: 'error',
                    content: res.msg,
                }); 
            }

        } catch(err) {
          //try 中出问题了，走这儿
          console.log("出错了，请检查:",err)
        }
        // 
    };
    
    return (
        <>
            {contextHolder}
            <Flex className="login" justify="center" align="center">
             <Row className="form" > 
                <Col span={24} >
                    <Row className="title">
                        <Col span={24}>
                            <h2>登录</h2>
                        </Col>
                    </Row>
                    
                    <Row className='form-control'>

                        <Col span={24}>
                            <Form
                                name="normal_login"
                                className="login-form"
                                initialValues={{ remember: true }}
                                onFinish={onFinish}
                            >

                                <Form.Item
                                    name="username"
                                    rules={[{ required: true, message: '请输入账号!' }]}
                                >
                                    <Input 
                                        prefix={<UserOutlined className="site-form-item-icon" />} 
                                        placeholder="用户名" 
                                    />
                                </Form.Item>

                                <Form.Item
                                    name="password"
                                    rules={[{ required: true, message: '请输入密码!' }]}
                                >
                                   

                                    <Input.Password placeholder="密码" prefix={<LockOutlined className="site-form-item-icon" />}/>
                                </Form.Item>

                                <Form.Item>
                                    <Form.Item name="remember" valuePropName="checked" noStyle>
                                        <Checkbox>记住密码</Checkbox>
                                    </Form.Item>
                                </Form.Item>

                                <Form.Item>
                                    {/* <Space> */}
                                        <Button type="primary" htmlType="submit" className="login-form-button">
                                            登录
                                        </Button>
                                        Or <a href="">立即注册</a>
                                    {/* </Space> */}
                                </Form.Item>
                            </Form>
                        </Col>
                    </Row>
                </Col>
             </Row>
        </Flex>
        </>
    )
}

export default Login;